<script setup>
import { ref } from 'vue'
import { onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const back1 = ref(false)
const back2 = ref(false)
const isEditing = ref(false) // 新增：标记是否为编辑状态
const editingIndex = ref(null) // 新增：当前编辑项的索引
const isLoading = ref(false)
const noticeData = ref([])

const columns = ref([
  { prop: 'index', label: '序号' },
  { prop: 'content', label: '内容' },
  { prop: 'time', label: '编辑时间' },
  { prop: 'operate', label: '操作' }
])

const selectedColumns = ref([
  'index',
  'content',
  'time', // 或者 'num'，保持统一
  'operate'
])

const resetColumns = () => {
  selectedColumns.value = columns.value.map(col => col.prop);
};

const form = ref({
  content: '',
  time: ''
})

const newly = () => {
  back1.value = true
  back2.value = true
  isEditing.value = false
  editingIndex.value = null
}

// 定义唯一的存储键名
const NOTICE_CENTER_STORAGE_KEY = 'notice-Data'

// 保存数据到 localStorage
const saveNoticeDataToLocal = () => {
  localStorage.setItem(NOTICE_CENTER_STORAGE_KEY, JSON.stringify(noticeData.value))
}

// 刷新功能
const triggerRefresh = async () => {
  isLoading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))

    // 从本地存储重新加载数据
    const savedData = localStorage.getItem(NOTICE_CENTER_STORAGE_KEY)
    if (savedData) {
      noticeData.value = JSON.parse(savedData)
    }

    ElMessage.success('刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败: ' + error.message)
  } finally {
    isLoading.value = false
  }
}

// 密度选项
const densityOptions = [
  { label: '默认', value: 'default', class: '' },
  { label: '中等', value: 'medium', class: 'medium-density' },
  { label: '紧凑', value: 'compact', class: 'compact-density' }
]

// 当前密度（从localStorage加载或使用默认值）
const currentDensity = ref(localStorage.getItem('table-density') || 'default')

// 切换密度并保存到localStorage
const toggleDensity = () => {
  const currentIndex = densityOptions.findIndex(opt => opt.value === currentDensity.value)
  const nextIndex = (currentIndex + 1) % densityOptions.length
  currentDensity.value = densityOptions[nextIndex].value
  localStorage.setItem('table-density', currentDensity.value)
}

onMounted(() => {
  // 加载表格数据
  const savedData = localStorage.getItem(NOTICE_CENTER_STORAGE_KEY)
  if (savedData) {
    noticeData.value = JSON.parse(savedData)
    nextId = noticeData.value.length + 1
  }

  // 加载密度设置
  const savedDensity = localStorage.getItem('table-density')
  if (savedDensity) {
    currentDensity.value = savedDensity
  }
})

const Cancel = () => {
  back1.value = false
  back2.value = false
  // 清空表单
  form.value = {
    content: '',
  }
}

// 生成唯一ID
let nextId = noticeData.value.length + 1

const sure = () => {
  isLoading.value = true
  try {
    // 验证内容是否填写
    if (!form.value.content.trim()) {
      ElMessage.error('请输入内容')
      isLoading.value = false
      return
    }

    const currentTime = new Date().toLocaleString() // 获取当前时间字符串

    const newItem = {
      id: nextId++,
      content: form.value.content,
      time: currentTime
    }

    if (isEditing.value) {
      // 编辑模式
      noticeData.value[editingIndex.value] = newItem
      ElMessage.success('编辑成功')
    } else {
      // 添加模式
      noticeData.value.push(newItem)
      ElMessage.success('添加成功')
    }

    saveNoticeDataToLocal()
    Cancel()
  } finally {
    isLoading.value = false
  }
}

// 删除轮播图
const deleteItem = (index) => {
  // 从数组中删除项目
  noticeData.value.splice(index, 1);
  // 立即更新本地存储
  saveNoticeDataToLocal();
  ElMessage.success('删除成功');
}

// 编辑轮播图
const editItem = (index) => {
  const item = noticeData.value[index]
  form.value = {
    content: item.content,
    time: item.time
  }
  back1.value = true
  back2.value = true
  isEditing.value = true
  editingIndex.value = index
}
</script>

<template>
  <el-breadcrumb style="margin: 0 0 20px 0" separator="/">
    <el-breadcrumb-item :to="{ path: '/system/notice'}">系统内容管理</el-breadcrumb-item>
    <el-breadcrumb-item>
      <a href="#">系统公告</a>
    </el-breadcrumb-item>
  </el-breadcrumb>
  <div class="text1">
    <span><strong>系统公告</strong></span>
  </div>
  <div class="border"
       :class="currentDensity === 'compact' ? 'compact-density' : currentDensity === 'medium' ? 'medium-density' : ''">
    <el-tooltip content="列设置" placement="top">
      <el-popover placement="bottom" trigger="click" width="150">
        <template #reference>
          <div class="iconfont icon-shezhi" style="margin-right: 16px; cursor: pointer;"></div>
        </template>
        <el-checkbox-group v-model="selectedColumns">
          <el-checkbox
              v-for="col in columns"
              :key="col.prop"
              :label="col.prop"
          >
            {{ col.label }}
          </el-checkbox>
        </el-checkbox-group>
        <div style="margin-top: 10px;">
          <el-button size="small" @click="resetColumns">重置</el-button>
        </div>
      </el-popover>
    </el-tooltip>
    <el-tooltip content="密度" placement="top">
      <div
          class="iconfont icon-midu"
          @click="toggleDensity"
          style="cursor: pointer"
      ></div>
    </el-tooltip>
    <el-tooltip content="刷新" placement="top">
      <div
          class="iconfont icon-shuaxin"
          @click="triggerRefresh"
          :class="{ 'refreshing': isLoading }"
          style="cursor: pointer"
      ></div>
    </el-tooltip>
    <div class="btn" @click="newly" style="cursor: pointer"><span>+</span> 新建</div>
    <table class="custom-table">
      <thead>
      <tr>
        <th v-if="selectedColumns.includes('index')">序号</th>
        <th v-if="selectedColumns.includes('content')">内容</th>
        <th v-if="selectedColumns.includes('time')">编辑时间</th>
        <th v-if="selectedColumns.includes('operate')">操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, index) in noticeData" :key="index">
        <td v-if="selectedColumns.includes('index')">{{ index + 1 }}</td>
        <td v-if="selectedColumns.includes('content')">{{ item.content }}</td>
        <td v-if="selectedColumns.includes('time')">{{ item.time }}</td>
        <td v-if="selectedColumns.includes('operate')" class="text2">
          <span style="cursor: pointer" @click="editItem(index)">编辑 </span>
          <span style="cursor: pointer" @click="deleteItem(index)">删除</span>
        </td>
      </tr>
      </tbody>
    </table>

    <!--    <div>-->
    <!--      <el-pagination-->
    <!--          :current-page="currentPage"-->
    <!--          :page-size="itemsPerPage"-->
    <!--          :total="totalItems"-->
    <!--          layout="total, prev, pager, next"-->
    <!--          @current-change="handlePageChange"-->
    <!--      />-->
    <!--      <p class="item-count">第{{ currentItem }}-{{ endItem }}条/总共{{ totalItems }}条</p>-->
    <!--    </div>-->
  </div>
  <div class="XJ" v-if="back1">
    <el-form :model="form" label-width="auto" style="max-width: 600px; margin: 15px;">
      <div style="margin: 0 0 0 20px;">{{ isEditing ? '编辑' : '添加' }}</div>
      <hr style="margin: 15px -15px 0 -15px">
      <el-form-item>
        <div>* 内容详情</div>
        <el-input v-model="form.content" placeholder="请输入" type="textarea" rows="3" />
      </el-form-item>
      <hr style="margin: 25px -15px 0 -15px">
      <el-form-item style="margin-top: 20px">
        <el-button type="primary" @click="sure">确定</el-button>
        <el-button @click="Cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="background" v-if="back2"></div>

</template>

<style scoped >
@import "//at.alicdn.com/t/c/font_4912316_bc79tia7gg9.css";
.text1{
  margin-bottom: 20px;
  span{
    font-size: 18px;
  }
}

.small-uploader :deep(.el-upload--picture-card) {
  width: 60px !important;
  height: 60px !important;
}

.XJ{
  width: 550px;
  height: 250px;
  position: fixed; /* 或 absolute */
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #FFFFFF;
  z-index: 1000;
}

.background{
  position: fixed; /* 覆盖整个视窗 */
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
}

.text2{
  span{
    font-size: 16px;
    color: #1990FF;
  }
}

.custom-table {
  width: 98%;
  margin: 55px auto;
  border-collapse: collapse;
}
.custom-table th, .custom-table td {
  padding: 10px;
  text-align: left;
  border: none;
  border-bottom: 1px solid #ddd;
  background-color: #FAFAFA;
}

.custom-table td{
  background-color: #fff;
}

.custom-table tr:nth-child(even) {
  background-color: #f2f2f2;
}

.border{
  &.medium-density {
    @extend %medium-density;
  }

  &.compact-density {
    @extend %compact-density;
  }


  background-size: cover;
  border: 1px solid #F0F0F0;
  background: #FFFFFF;

  .iconfont{
    float: right;
    font-size: 16px;
    margin: 15px 10px 0 0;
  }
}

.btn{
  width: 70px;
  height: 30px;
  border-radius: 2px;
  font-size: 12px;
  text-align: center;
  line-height: 23px;
  background-color: #1990FF;
  color: #fff;
  float: right;
  margin: 15px 15px 0 0;

  span{
    font-size: 18px;
  }
}

.iconfont{
  font-size: 12px;
  line-height: 25px;
}

.iconfont:hover{
  color: #1777FE;
}

.icon-shuaxin {
  transition: transform 0.3s;
}

.icon-shuaxin.refreshing {
  animation: spin 0.8s linear infinite;
  color: #1990FF;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 中等密度样式 */
.medium-density .custom-table th,
.medium-density .custom-table td {
  padding: 8px 10px;
}

.medium-density .custom-table {
  font-size: 13px;
}

/* 紧凑密度样式 */
.compact-density .custom-table th,
.compact-density .custom-table td {
  padding: 5px 8px;
}

.compact-density .custom-table {
  font-size: 12px;
}

.compact-density .custom-table img {
  width: 40px;
  height: 24px;
}

.btn:hover{
  background: #40A9FF;
}

hr{
  border: none; /* 移除默认样式 */
  border-top: 1px solid #F0F0F0; /* 设置顶部边框颜色 */
}
</style>